import Fly from 'flyio/dist/npm/wx'
const fly = new Fly()
const host =
  process.env.NODE_ENV === 'development'
    ? 'http://test.v2.ybangy.net'
    : 'https://v2.ybangy.net'
fly.config.baseURL = host

// 添加请求拦截器
fly.interceptors.request.use((request) => {
  request.headers['clientId'] = uni.getStorageSync('clientId')
    ? uni.getStorageSync('clientId')
    : 'factory_wxa'
  request.headers['token'] = uni.getStorageSync('token')

  uni.showLoading({
    title: '加载中',
    mask: true,
  })
  return request
})

// 添加响应拦截器
fly.interceptors.response.use(
  (response) => {
    uni.hideLoading()
    return response // 请求成功之后将返回值返回
  },
  (err) => {
    // 请求出错，根据返回状态码判断出错原因
    console.log(err, 'response')
    uni.hideLoading()
    if (err.status === 401 || err.status === 403) {
      uni.showModal({
        title: '温馨提示',
        content: err.response.data.errorMsg,
        confirmText: '确定',
        confirmColor: '#5880ff',
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            uni.removeStorageSync('token')
            uni.removeStorageSync('userInfo')
            uni.removeStorageSync('factoryinfo')
            uni.reLaunch({
              url: '/pages/login/login',
            })
          }
        },
      })
    }
  }
)

export default fly
